#! /usr/bin/python
# encoding=utf-8
# Created by Fenglu Niu on 2025/5/27 9:37
import json
from datetime import datetime

from sqlmodel import Session

import common
import db
from api.entity import Case, Person, CaseResult, CaseFeedback, CaseFlow, CaseApplyRecord
from api.service.case_apply_record_service import CaseApplyRecordService
from api.service.case_feedback_service import CaseFeedbackService
from api.service.case_flow_service import CaseFlowService
from api.service.case_result_service import CaseResultService
from api.service.case_service import CaseService
from api.service.person_service import PersonService
from crawler import Crawler


class SysService(object):
    @staticmethod
    def start():
        crawler = Crawler()
        session = next(db.get_session())
        # 取出最新的case
        latest_case = CaseService.get_latest_case(session)
        # 取case列表
        page = 1
        case_list_json = crawler.get_case_list(1)
        total_page = case_list_json['data']['totalPages']
        if total_page <= 0:
            return
        break_outer = False
        while page <= total_page:
            case_list_json = crawler.get_case_list(page)
            case_list = case_list_json['data']['content']
            for case_json in case_list:
                if latest_case and str(case_json['id']) == str(latest_case.id):
                    break_outer = True
                    break
                # 处理案件信息
                SysService.handle_case(case_json, session)
                # 处理案件当事人
                SysService.handle_case_person(case_json, session)
                # 处理案件结果
                SysService.handle_case_result(case_json['id'], session)
                # 处理案件反馈
                SysService.handle_case_feedback(case_json['id'], session)
                # 处理案件流程
                SysService.handle_case_flow(case_json['id'], session)
                # 处理案件申请记录
                SysService.handle_case_apply_record(case_json['id'], session)
            if break_outer:
                break
            page += 1

    @staticmethod
    def handle_case(case_json, session: Session):
        case = Case()
        case.id = case_json['id']
        crawler = Crawler()
        case_info_json = crawler.get_case_info(case.id)
        case.case_task_id = case_json['caseTaskId']
        case.input_unit_id = case_json['inputUnitId']
        case.input_unit_name = case_json['inputUnitName']
        case.area_name = case_json['areaName']
        case.canal_name = case_json['canalName']
        case.case_level = case_json['caseLevel']
        case.case_ref = case_json['caseRef']
        case.case_type = case_json['caseType']
        case.case_type_name = case_json['caseTypeName']
        case.mediate_unit_name = case_json['mediateUnitName']
        case.mediate_unit_id = case_json['mediateUnitId']
        case.assist_unit_name = case_json['assistUnitName']
        case.assist_unit_id = case_json['assistUnitId']
        case.status = case_json['status']
        case.status_name = case_json['statusName']
        case.medi_result_name = case_json['mediResultName']
        case.plaintiffs = case_json['plaintiffs']
        case.defendants = case_json['defendants']
        case.occur_time = datetime.fromisoformat(case_json['occurTime']).astimezone()
        case.major_status = case_json['majorStatus']
        case.is_risk = case_json['isRisk']
        case.case_claim = case_json['caseClaim']
        case.case_des = case_json['caseDes']
        case.addr = case_json['addr']
        case.amount = case_json['amount']
        case.people_num = case_json['peopleNum']
        case.visit_way_name = case_info_json['visitWayName']
        case.visit_people_num = case_info_json['visitPeopleNum']
        if case_info_json['visitTime']:
            case.visit_time = datetime.fromisoformat(case_info_json['visitTime']).astimezone()
        case.create_time = datetime.fromisoformat(case_json['createTime']).astimezone()
        case.close_time = datetime.fromisoformat(case_json['closeTime']).astimezone()
        CaseService.create_case(case, session)

    @staticmethod
    def handle_case_person(case_json, session):
        id = case_json['id']
        crawler = Crawler()
        case_info_json = crawler.get_case_info(id)
        person_list = case_info_json['personList']
        persons = []
        for person_json in person_list:
            person = Person()
            person.id = person_json['id']
            person.case_id = id
            person.per_type = person_json['perType']
            person.per_type_name = person_json['perTypeName']
            person.per_class_name = person_json['perClassName']
            person.true_name = person_json['trueName']
            person.mobile = person_json['mobile']
            person.sex_name = person_json['sexName']
            person.nation_name = person_json['nationName']
            person.certi_type_name = person_json['certiTypeName']
            person.certi_no = person_json['certiNo']
            person.addr = person_json['addr']
            person.place_addr = person_json['placeAddr']
            person.age = person_json['age']
            person.work_unit = person_json['workUnit']
            person.extreme = person_json['extreme']
            persons.append(person)
        PersonService.create_person(persons, session)

    @staticmethod
    def handle_case_result(case_id, session):
        crawler = Crawler()
        case_result_json = crawler.get_case_result(case_id)
        if case_result_json:
            case_result = CaseResult()
            case_result.id = case_result_json['id']
            case_result.case_id = case_id
            case_result.medi_result_name = case_result_json['mediResultName']
            case_result.mediator = case_result_json['mediator']
            case_result.mediate_unit_name = case_result_json['mediateUnitName']
            case_result.assist_unit_name = case_result_json['assistUnitName']
            case_result.accept_time = datetime.fromisoformat(case_result_json['acceptTime']).astimezone()
            case_result.close_time = datetime.fromisoformat(case_result_json['closeTime']).astimezone()
            case_result.handle_content = case_result_json['handleContent']
            case_result.windup_content = case_result_json['windupContent']
            case_result.agree_type_name = case_result_json['agreeTypeName']
            case_result.agree_content = case_result_json['agreeContent']
            # 处理附件
            file_list = case_result_json['fileInfoBaseDTOList']
            files = []
            base_url = 'https://zfw-dyh.by.gov.cn/gzdyh-sys'
            if file_list and len(file_list) > 0:
                for file_json in file_list:
                    file = {}
                    file.setdefault('id', file_json['id'])
                    file.setdefault('name', file_json['name'])
                    file.setdefault('show_url', base_url + file_json['showUrl'])
                    file.setdefault('down_url', base_url + file_json['downUrl'])
                    file.setdefault('suffix', file_json['suffix'])
                    files.append(file)
            case_result.agree_files = json.dumps(files, ensure_ascii=False)
            CaseResultService.create_result(case_result, session)
        pass

    @staticmethod
    def handle_case_feedback(case_id, session):
        crawler = Crawler()
        case_feedback_list = crawler.get_case_feedback_list(case_id)
        case_feedbacks = []
        for case_feedback_json in case_feedback_list:
            case_feedback = CaseFeedback()
            case_feedback.id = case_feedback_json['id']
            case_feedback.case_id = case_id
            case_feedback.handle_unit_name = case_feedback_json['handleUnitName']
            case_feedback.handle_user_name = case_feedback_json['handleUserName']
            case_feedback.handle_content = case_feedback_json['handleContent']
            case_feedback.create_time = datetime.strptime(case_feedback_json['createTime'], '%Y-%m-%d %H:%M')
            if case_feedback_json['fileInfoList']:
                common.get_logger().info('案件id={}有附件，请处理', case_id)
            case_feedbacks.append(case_feedback)
        CaseFeedbackService.create_feedback(case_feedbacks, session)

    @staticmethod
    def handle_case_flow(case_id, session):
        crawler = Crawler()
        case_flow_data = crawler.get_case_flow_list(case_id)
        case_flow_list = case_flow_data['handleCaseFlowList']
        case_flows = []
        for case_flow_json in case_flow_list:
            case_flow = CaseFlow()
            case_flow.case_id = case_id
            case_flow.node_show_name = case_flow_json['nodeShowName']
            case_flow.handle_unit_name = case_flow_json['handleUnitName']
            case_flow.handle_user_name = case_flow_json['handleUserName']
            case_flow.handle_time = datetime.fromisoformat(case_flow_json['handleTime']).astimezone()
            case_flow.handle_notes = case_flow_json['handleNotes']
            case_flow.medi_result_name = case_flow_json['mediResultName']
            case_flow.audit_result_name = case_flow_json['auditResultName']
            case_flows.append(case_flow)
        CaseFlowService.create_flow(case_flows, session)

    @staticmethod
    def handle_case_apply_record(case_id, session):
        crawler = Crawler()
        case_apply_record_list = crawler.get_case_apply_record(case_id)
        case_apply_records = []
        for case_apply_record_json in case_apply_record_list:
            case_apply_record = CaseApplyRecord()
            case_apply_record.id = case_apply_record_json['object']['id']
            case_apply_record.case_id = case_id
            case_apply_record.type = case_apply_record_json['type']
            case_apply_record.audit_result_name = case_apply_record_json['object']['auditResultName']
            case_apply_record.medi_result_name = case_apply_record_json['object']['mediResultName']
            case_apply_record.windup_content = case_apply_record_json['object']['windupContent']
            case_apply_record.apply_time = datetime.fromisoformat(case_apply_record_json['object']['applyTime']).astimezone()
            case_apply_record.apply_unit_name = case_apply_record_json['object']['applyUnitName']
            case_apply_record.apply_user_name = case_apply_record_json['object']['applyUserName']
            case_apply_record.audit_content = case_apply_record_json['object']['auditContent']
            case_apply_record.audit_time = datetime.fromisoformat(case_apply_record_json['object']['auditTime']).astimezone()
            case_apply_record.audit_unit_name = case_apply_record_json['object']['auditUnitName']
            case_apply_record.audit_user_name = case_apply_record_json['object']['auditUserName']
            case_apply_records.append(case_apply_record)
        CaseApplyRecordService.create_apply_record(case_apply_records, session)
        pass
